package com.chz.SupermarketMS.controllers;

import com.chz.SupermarketMS.dao.CommodityRepository;
import com.chz.SupermarketMS.dao.KindRepository;
import com.chz.SupermarketMS.dto.KindCommodities;
import com.chz.SupermarketMS.entities.Commodity;
import com.chz.SupermarketMS.entities.Kind;
import com.chz.SupermarketMS.service.CommodityService;
import com.chz.SupermarketMS.service.KindService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("kinds")
public class KindController {

    @Autowired
    KindService kindService;

    @Autowired
    KindRepository kindRepository;

    @Autowired
    CommodityService commodityService;

    @Autowired
    CommodityRepository commodityRepository;

    @GetMapping
    public String displayKinds(Model model){

        List<Kind> kinds = kindService.getAll();
        model.addAttribute("kinds",kinds);

//        List<KindCommodities> kindCommodities = kindRepository.kindCommodities();
//        model.addAttribute("kindCommodities",kindCommodities);

        return "kinds/list-kinds";
    }

    @GetMapping("/new")
    public String displayKindForm(Model model){

        Kind aKind = new Kind();
        List<Commodity> commodities = commodityService.getAll();
        model.addAttribute("kind",aKind);
        model.addAttribute("allCommodities",commodities);

        return "kinds/new-kind";
    }

    @PostMapping("/save")
    public String createKind(Model model, @RequestParam List<Long> commodities, @Valid Kind kind, Errors errors){
        if (errors.hasErrors()) return "kinds/new-kind";

        kindService.save(kind);

        Iterable<Commodity> chosenCommodities = commodityRepository.findAllById(commodities);
        for (Commodity commodity : chosenCommodities){
            commodity.setKind(kind);
            commodityRepository.save(commodity);
        }
        return "redirect:/kinds";
    }
    @GetMapping("/update")
    public String displayKindUpdateForm(@RequestParam("id") long theId, Model model) {
        Kind theKind = kindService.findByKindId(theId);
        model.addAttribute("kind", theKind);
        return "kinds/new-kind";
    }

    @GetMapping("/delete")
    public String deleteKind(@RequestParam("id")long theId, Model model) {
        Kind theKind = kindService.findByKindId(theId);
        kindService.delete(theKind);
        return "redirect:/kinds";
    }




}
